/*
 * @Author: zyk 997610780@qq.com
 * @Date: 2022-10-21 15:27:35
 * @LastEditors: zyk 997610780@qq.com
 * @LastEditTime: 2022-10-26 15:04:10
 * @FilePath: \fifty-small-projects\46答题应用程序\46.js
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
const quizData = [
  {
    question: "哪种语言可以在浏览器中运行?",
    a: "Java",
    b: "C",
    c: "Python",
    d: "JavaScript",
    correct: "d",
  },
  {
    question: "CSS是什么?",
    a: "中央样式表",
    b: "层叠样式表",
    c: "级联简单的表",
    d: "汽车帆船",
    correct: "b",
  },
  {
    question: "HTML是什么?",
    a: "超文本标记语言",
    b: "超文本减价语言",
    c: "Hyperloop机器语言",
    d: "直升机，航站楼，摩托艇，兰博基尼",
    correct: "a",
  },
  {
    question: "JavaScript是哪一年发布的?",
    a: "1996",
    b: "1995",
    c: "1994",
    d: "以上都不是",
    correct: "b",
  },
];

// 当前题目
let cur_quiz = 0
let answer_items = document.querySelectorAll('.answer_item')
answer_items = Array.prototype.slice.call(answer_items,0)

let quiz_hd = document.querySelector('.quiz_hd')
let sub_btn = document.querySelector('.sub_btn')
let reset_btn = document.querySelector('.reset_btn')
// 选中的答案
let select_a = []
function loadQuiz(is_init) {
  quiz_hd.innerText = quizData[cur_quiz].question
  answer_items.forEach(item=>{
    if(is_init){
      item.firstElementChild.checked = false
    }
    let keys = Object.keys(quizData[cur_quiz])
    if(keys.includes(item.getAttribute('data-option'))){
      let i = keys.indexOf(item.getAttribute('data-option'))
      item.lastElementChild.innerText = quizData[cur_quiz][keys[i]]
    }
  })
}

loadQuiz()

// 展示结果
function showResult(){
  let result_title = document.querySelector('.result .title')
  result_title.parentNode.classList.remove('hide')
  sub_btn.parentNode.classList.add('hide')
  console.log(select_a);
  let count = 0
  quizData.forEach((item,index)=>{
    if(item.correct == select_a[index]){
      count++
    }
  })

  result_title.innerText = `You answered ${count}/${quizData.length} questions correctly`
}

sub_btn.addEventListener('click',()=>{
    let i = answer_items.findIndex(item => item.firstElementChild.checked)
    if (i != -1) {
      cur_quiz++
      select_a.push(answer_items[i].getAttribute('data-option'))
      if (cur_quiz <= quizData.length - 1) {
        loadQuiz(true)
      }else{
        showResult()
      }
    }else{
      alert('请选择您的答案!')
    }
})

reset_btn.addEventListener('click',()=>{
  select_a.length = 0
  cur_quiz = 0
  loadQuiz(true)

  reset_btn.parentNode.classList.add('hide')
  sub_btn.parentNode.classList.remove('hide')
})